package rpc01;


import com.hl.rpc.common.User;
import com.hl.rpc.service.IUserService;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by yuanhailong on 2021/10/30.
 */
public class Server {

    private static boolean running=true;

    public static void main(String[] args) throws Exception{

        ServerSocket serverSocket=new ServerSocket(9999);

        System.out.println("rpc01 服务端启动...");
        while (running){
            Socket socket=serverSocket.accept();
            process(socket);
            socket.close();
        }
        serverSocket.close();
    }


    private static void process(Socket socket) throws Exception{
        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        DataInputStream dataInputStream = new DataInputStream(inputStream);
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

        int id=dataInputStream.readInt();  //读取客户端发送过来的ID
        System.out.println("服务端接收到客户端ID:"+id);
        IUserService userService=new UserServiceImp();
        User user = userService.findUserById(id);

        //这里写可以有很多种方式，理解为数据传输协议
        dataOutputStream.writeInt(user.getId());
        dataOutputStream.writeUTF(user.getName());
        dataOutputStream.flush();
    }
}
